////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;


using RPSDAL;
using RPSDAL.CollectionClasses;
using RPSDAL.FactoryClasses;
using RPSDAL.HelperClasses;
using RPSDAL.DaoClasses;
using RPSDAL.EntityClasses;
using RPSDAL.RelationClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;
using Winnovative.WnvHtmlConvert;



public partial class AssignedLetterList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Session["CHECKED_ITEMS"] = null;
            Session["FILTER"] = null;

            grdLetters.PageSize = Parameters.PageSize; 
           
            btnCheckAll.Attributes.Add("OnClick", "this.value=CheckAll('aspnetForm');return false;");
            LoadLetters();

            if (Request.Form["txtAction"] != null)
            {
                if (Request.Form["txtAction"] == "print")
                {
                    // all letters were printed successfully
                    MarkLettersAsSent();
                }
                else
                {
                    LoadLettersForReprint();
                }
            }
        }
    }

    private void LoadLetters()
    {
        DataTable dtFields = new DataTable();
        ResultsetFields fields = new ResultsetFields(5);

        fields.DefineField(LetterFieldIndex.LetterId, 0, "LetterId");
        fields.DefineField(LetterFieldIndex.LetterName, 1, "LetterName");
        fields.DefineField(BusinessRuleFieldIndex.From, 2, "From");
        fields.DefineField(BusinessRuleFieldIndex.To, 3, "DaysTo");
        fields.DefineField(ContactFieldIndex.ContactVisitDate, 4, "ContactVisitDate");

        RelationCollection relations = new RelationCollection();
        relations.Add(LetterEntity.Relations.BusinessRuleEntityUsingBusinessRulesId);
        relations.Add(LetterEntity.Relations.ContactEntityUsingContactId);

        fields[2].ExpressionToApply = new Expression(ContactFields.ContactVisitDate, ExOp.Add, BusinessRuleFields.From);
        fields[3].ExpressionToApply = new Expression(ContactFields.ContactVisitDate, ExOp.Add,BusinessRuleFields.To);

        IPredicateExpression filter = new PredicateExpression();
        filter.Add(LetterFields.Sent == false);

        TypedListDAO dao = new TypedListDAO();
        SortExpression sortExp = new SortExpression(new SortClause(fields["DaysTo"], SortOperator.Descending));
        dao.GetMultiAsDataTable(fields, dtFields, 0, sortExp, filter, relations, false, null, null, 0, 0);

        grdLetters.DataSource = dtFields;
        grdLetters.DataBind();
    }


    #region actions

    private void MarkLettersAsSent()
    { }

    private void LoadLettersForReprint()
    { }
   
    #endregion actions

    protected void btnPrint_Click(object sender, EventArgs e)
    {
        Global.UserLogSave(Parameters.LoggedUser, "Print Letters");
        if (btnPrint.Text == "Print")
        {
            ArrayList files = new ArrayList();
            IPredicateExpression filter = new PredicateExpression();

            for (int i = 0; i < grdLetters.Rows.Count; i++)
            {
                if (((CheckBox)grdLetters.Rows[i].Cells[2].FindControl("ckLetter")).Checked)
                {
                    int letterId = 0;
                    if (Int32.TryParse(((TextBox)grdLetters.Rows[i].Cells[2].FindControl("idLetter")).Text, out letterId))
                    {
                        filter.AddWithOr(LetterFields.LetterId == letterId);
                        LetterEntity eLetter = new LetterEntity(letterId);
                        string filePath = CreateHTMLLetter(eLetter);
                        files.Add(filePath);
                    }
                }
            }

            ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
            if (categoryIDList != null && categoryIDList.Count > 0)
            {
                for (int i = 0; i < categoryIDList.Count; i++) 
                {
                    int letterIdPrevious = (int)categoryIDList[i];
                    filter.AddWithOr(LetterFields.LetterId == letterIdPrevious);
                    LetterEntity eLetter = new LetterEntity(letterIdPrevious);
                    string filePath = CreateHTMLLetter(eLetter);
                    files.Add(filePath);
                }

                /*foreach (GridViewRow row in grdLetters.Rows)
                {
                    int index = (int)(grdLetters.DataKeys[row.RowIndex].Value);
                    if (categoryIDList.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)row.FindControl("ckLetter");
                        myCheckBox.Checked = true;

                    }
                }*/
            }

            Session["CHECKED_ITEMS"] = null;
            Session["FILTER"] = filter;

            MergeLetters(files);

            if (files.Count > 0)
            {
                files[0] = Methods.auxLetter(MapPath("PDF"), "", "html");
                for (int i = 0; i < files.Count; i++)
                {
                    if (File.Exists(files[i].ToString()))
                    {
                        File.Delete(files[i].ToString());
                    }
                }

                FileStream pdfFile = new FileStream(Methods.auxLetter(MapPath("PDF"), "", "pdf"), FileMode.Open);
                byte[] downloadBytes = new byte[(int)pdfFile.Length];
                pdfFile.Read(downloadBytes, 0, (int)pdfFile.Length);
                pdfFile.Close();


                Response.Write("<script>window.open('" + PageName() + "PDF/letter.pdf" + "','_new', '');</script>");

                DataTable dtFields = new DataTable();
                ResultsetFields fields = new ResultsetFields(5);

                fields.DefineField(LetterFieldIndex.LetterId, 0, "LetterId");
                fields.DefineField(LetterFieldIndex.LetterName, 1, "LetterName");
                fields.DefineField(BusinessRuleFieldIndex.From, 2, "From");
                fields.DefineField(BusinessRuleFieldIndex.To, 3, "DaysTo");
                fields.DefineField(ContactFieldIndex.ContactVisitDate, 4, "ContactVisitDate");

                fields[2].ExpressionToApply = new Expression(ContactFields.ContactVisitDate, ExOp.Add, BusinessRuleFields.From);
                fields[3].ExpressionToApply = new Expression(ContactFields.ContactVisitDate, ExOp.Add, BusinessRuleFields.To);

                RelationCollection relations = new RelationCollection();
                relations.Add(LetterEntity.Relations.BusinessRuleEntityUsingBusinessRulesId);
                relations.Add(LetterEntity.Relations.ContactEntityUsingContactId);

                filter.Add(LetterFields.Sent == false);

                TypedListDAO dao = new TypedListDAO();
                SortExpression sortExp = new SortExpression(new SortClause(fields["DaysTo"], SortOperator.Descending));
                dao.GetMultiAsDataTable(fields, dtFields, 0, sortExp, filter, relations, false, null, null, 0, 0);

                grdLetters.Columns[4].HeaderText = "Printed correctly";
                grdLetters.DataSource = dtFields;
                grdLetters.PageIndex = 0;
                grdLetters.DataBind();

                lblQuestion.Style["display"] = "inline";
                lblWarning.Style["display"] = "none";
                btnPrint.Text = "Save";
            }
            else 
            {
                lblWarning.Style["display"] = "inline";
            }
        }
        else
        {
            // save checked letters and redirect to the initial page
            for (int i = 0; i < grdLetters.Rows.Count; i++)
            {
                if (((CheckBox)grdLetters.Rows[i].Cells[2].FindControl("ckLetter")).Checked)
                {
                    int letterId = 0;
                    if (Int32.TryParse(((TextBox)grdLetters.Rows[i].Cells[2].FindControl("idLetter")).Text, out letterId))
                    {
                        LetterEntity eLetter = new LetterEntity(letterId);
                        eLetter.Sent = true;
                        eLetter.SendDate = DateTime.Now;
                        eLetter.Save();

                        ContactHistoryEntity eContactHistory = new ContactHistoryEntity();
                        eContactHistory.ContactId = eLetter.ContactId;
                        eContactHistory.LetterId = eLetter.LetterId;
                        eContactHistory.Time = eLetter.SendDate;
                        eContactHistory.Type = Parameters.LETTER_TYPE;
                        eContactHistory.BusinessRuleId = eLetter.BusinessRulesId;
                        eContactHistory.Save();
                    }
                }
            }
            Response.Redirect("AssignedLetterList.aspx");
        }

        /*
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "binary/octet-stream");
        response.AddHeader("Content-Disposition",
            "attachment; filename=Letter.pdf; size=" + downloadBytes.Length.ToString());
        response.Flush();
        response.BinaryWrite(downloadBytes);
        response.Flush();
        response.End();
         */
    }



    /// <summary>
    /// create a HTML file from a letter
    /// </summary>
    /// <param name="eLetter"></param>
    private string CreateHTMLLetter(LetterEntity eLetter)
    {
        string htmlBody = "<html>" + eLetter.LetterBody + "</html>";
        StreamWriter htmlFile = new StreamWriter(Methods.auxLetter(MapPath("PDF"), eLetter.LetterId.ToString(), "html"), false);
        htmlFile.Write(htmlBody);
        htmlFile.Flush();
        htmlFile.Close();

        return Methods.auxLetter(MapPath("PDF"), eLetter.LetterId.ToString(),"html");


    }

    private void MergeLetters(ArrayList filePaths)
    {
        MemoryStream helperPdfStream = null;
        ArrayList memoryStreams = new ArrayList();
        
        try
        {
            if (filePaths.Count > 0)
            {
                string rootPath = Path.GetDirectoryName(filePaths[0].ToString()) + "\\";
                File.Move(filePaths[0].ToString(), rootPath + "letter.html");
                File.Delete(filePaths[0].ToString());

                PdfConverter pdfConverter = new PdfConverter();
                pdfConverter.LicenseKey = "nNvrZ7OeCsyX5s8Kv3IG70/JU5F3XEDrjC/4qkkfSD4pxNaNnHJcEC5MIrtWv0Up";
                for (int i = 1; i < filePaths.Count; i++)
                {
                    byte[] docHelperBytes = pdfConverter.GetPdfBytesFromHtmlFile(filePaths[i].ToString());
                    helperPdfStream = new MemoryStream(docHelperBytes);
                    memoryStreams.Add(helperPdfStream);
                }

                //set the PDF streams to be appended to the conversion result 
                // of the first URL
                pdfConverter.PdfDocumentOptions.AppendPDFStreamArray = new Stream[memoryStreams.Count];
                for (int i = 0; i < memoryStreams.Count; i++)
                {
                    pdfConverter.PdfDocumentOptions.AppendPDFStreamArray[i] = (Stream)memoryStreams[i];
                }


                //Produce the final PDF as a merge of the URL1, URL2 and URL 3 conversions
                string outFilePath = Methods.auxLetter(MapPath("PDF"), "", "pdf");
                pdfConverter.SavePdfFromUrlToFile(PageName() + "PDF/letter.html", outFilePath);

            }
        }
        catch
        {
            return;
        }
        finally
        {
            if (helperPdfStream != null)
                helperPdfStream.Close();
        }

    }
    private string PageName()
    {
        string url = Request.Url.AbsoluteUri;
        string[] fragments = url.Split('/');
        return url.Replace(fragments[fragments.Length - 1], "");
    }

    protected void grdLetters_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        RememberOldValues();
        grdLetters.PageIndex = e.NewPageIndex;
        LetterCollection cLetters = new LetterCollection();
   /*     IPredicateExpression filter = new PredicateExpression();
        filter.Add(LetterFields.Sent == false);*/
        cLetters.GetMulti((IPredicateExpression)Session["FILTER"]);

        grdLetters.DataSource = cLetters;
        grdLetters.DataBind();
        RePopulateValues();

    }

    private void RememberOldValues()
    {
        ArrayList categoryIDList = new ArrayList();
        int index = -1;
        foreach (GridViewRow row in grdLetters.Rows)
        {
            index = (int)(grdLetters.DataKeys[row.RowIndex].Value);
            bool result = ((CheckBox)row.FindControl("ckLetter")).Checked;

            // Check in the Session
            if (Session["CHECKED_ITEMS"] != null)
                categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
            if (result)
            {
                if (!categoryIDList.Contains(index))
                    categoryIDList.Add(index);
            }
            else
                categoryIDList.Remove(index);
        }
        if (categoryIDList != null && categoryIDList.Count > 0)
            Session["CHECKED_ITEMS"] = categoryIDList;
    }

    private void RePopulateValues()
    {
        ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
        if (categoryIDList != null && categoryIDList.Count > 0)
        {
            foreach (GridViewRow row in grdLetters.Rows)
            {
                int index = (int)(grdLetters.DataKeys[row.RowIndex].Value);
                if (categoryIDList.Contains(index))
                {
                    CheckBox myCheckBox = (CheckBox)row.FindControl("ckLetter");
                    myCheckBox.Checked = true;
                }
            }
        }
    }    

}
